extends Unit
class_name Player

@export var dash_duration : float = 0.5
@export var dash_speed_multi : float = 2.5
@export var dash_cooldown : float = 2.5


@onready var dash_timer: Timer = $DashTimer
@onready var dash_cooldown_timer: Timer = $DashCooldownTimer
@onready var collision: CollisionShape2D = $CollisionShape2D
@onready var trail: Trail = $Trail



var move_dir : Vector2

var is_dashing : bool = false
var dash_available : bool = true


func _ready() -> void:
	dash_timer.wait_time = dash_duration
	dash_cooldown_timer.wait_time = dash_cooldown

func _process(delta: float) -> void:
	move_dir = Input.get_vector("move_left","move_right","move_up","move_down")
	
	var current_velocity := move_dir * stats.speed 
	if is_dashing :
		current_velocity *= dash_speed_multi
	position += current_velocity * delta
	position.x = clamp(position.x, -500, 500)
	position.y = clamp(position.y, -250, 250)
	
	if can_dash() :
		start_dash()
	
	update_animations()
	
func update_animations() -> void :
	var anim_name = ""
	if move_dir.length_squared() > 0 :
		anim_name = animation_name(move_dir, "move")
	else:
		anim_name = animation_name(move_dir, "idle")
	anim_player.play(anim_name)



func start_dash() -> void :
	is_dashing = true;
	trail.start_trail()
	sprite.modulate.a = 0.5
	# 禁用碰撞器（在游戏运行时设置碰撞，似乎有点特殊，需要用set_deferred）
	collision.set_deferred("disabled", true) 
	dash_timer.start()

func can_dash() -> bool :
	return !is_dashing &&\
	 dash_cooldown_timer.is_stopped() &&\
	Input.is_action_just_pressed("dash") &&\
	move_dir != Vector2.ZERO


func _on_dash_timer_timeout() -> void:
	is_dashing = false
	sprite.modulate.a = 1.0
	move_dir = Vector2.ZERO
	collision.set_deferred("disabled", false)
	dash_cooldown_timer.start()
